<?php
/**
 * 后台标签管理
 * @author caoge
 * @version 2012-7-27
 */
class ArticleTagAction extends AdminBaseAction{
	/**
	 * 标签列表
	 * 
	 * @author caoge
	 * @version 2012-7-27
	 */
	public function index(){
		$nowPage = $this->_get('p','',1);
		$ArticleTag = D(ArticleTag);
		$where = 'del_flag=0';
		import("ORG.Util.Page");
		$count = $ArticleTag->where($where)->count();
		$p = new Page($count,10);
		
		$list = $ArticleTag->relation(true)->where($where)
		->limit($p->firstRow.','.$p->listRows)->select();
		$this->assign('page',$p->show());
		$this->assign('nowPage',$nowPage);
		$this->assign('list',$list);
		$this->display();
	}
	
	/**
	 * 添加或者编辑标签
	 * 
	 * @author caoge
	 * @version 2012-7-27
	 */
	public function edit(){
		$nowPage = $this->_get('p','',1);
		$tagId = $this->_get('tagId','',0);
		$tagName = $this->_post('tagName','strip_tags','');
		if ($tagName != ''){
			$data = array(
					'tag_name'=>$tagName
			);
			$ArticleTag = D(ArticleTag);
			if ($tagId == 0){
				//新增
				$ArticleTag->data($data)->add();
				$this->success('添加成功',__APP__.'/ArticleTag/index/?&p='.$nowPage);
			}else {
				$updateCondition['tag_id'] = $tagId;
				$ArticleTag->where($updateCondition)->data($data)->save();
				$this->success('编辑成功',__APP__.'/ArticleTag/index/?&p='.$nowPage);
			}
		}else {
			if ($tagId == 0){
				$actionTile = '添加新标签';
			}else {
				$ArticleTag = D(ArticleTag);
				$condition['tag_id'] = $tagId;
				$tagInfo = $ArticleTag->where($condition)->find();
				if (!$tagInfo){
					$this->error('类别不存在',__APP__.'/ArticleTag/index/');
				}
				$actionTile = '编辑标签';
				$this->assign('tagInfo',$tagInfo);
			}
			$this->assign('nowPage',$nowPage);
			$this->assign('actionTile',$actionTile);
			$this->display();
		}
	}
	
	/**
	 * 删除标签
	 * 
	 * @author caoge
	 * @version 2012-7-27
	 */
	public function delete(){
		$nowPage = $this->_get('p','',1);
		$tagId = $this->_get('tagId','',0);
		$ArticleTag = D(ArticleTag);
		$condition['tag_id'] = $tagId;
		$data['del_flag'] = 1;
		$ArticleTag->where($condition)->data($data)->save();
		$ArticleTagRelationship = D(ArticleTagRelationship);
		$ArticleTagRelationship->where(array('tag_id'=>$tagId))->delete();
		$this->success('删除成功',__APP__.'/ArticleTag/index/?&p='.$nowPage);
	}
	
	/**
	 * 异步检查此标签下有多少篇文章，返回信息
	 * 
	 * @author caoge
	 * @version 2012-7-27
	 */
	public function ajaxTagDeleteCheck(){
		$tagId = $this->_get('tagId','',0);
		$arrayToJs = array('status'=>1,'msg'=>'确定删除吗？');
		if ($tagId != 0){
			$ArticleTagRelationship = D(ArticleTagRelationship);
			$condition['tag_id'] = $tagId;
			$count = $ArticleTagRelationship->where($condition)->count();
			if ($count > 0){
				$arrayToJs['status'] = 0;
				$arrayToJs['msg'] = '此标签被'.$count.'篇文章使用，确定删除吗？';
			}
		}
		echo json_encode($arrayToJs);
	}
}